package com.wm.yigongfang.common.jwt;

import com.wm.yigongfang.common.config.ServiceException;

/**
 * @author zp
 * @version 1.0
 * @date 2021/5/2 0:48
 */
public class UserContextHolder {
    private static final InheritableThreadLocal<UserContext> context = new InheritableThreadLocal<>();

    public static void set(UserContext userContext) {
        if (context.get() != null && (context.get() != userContext)) {
            clear();
        }
        if (context.get() == null) {
            context.set(userContext);
        }
    }

    public static UserContext get() {
        UserContext userContext = context.get();
        if (userContext == null) {
            throw new ServiceException("未登录或者未传登录token");
        }
        return userContext;
    }

    public static void clear() {
        if (context != null && context.get() != null) {
            context.remove();
        }
    }
}
